package problem54_Spiral_Matrix;

import java.util.LinkedList;
import java.util.List;

public class MySolution {
	public List<Integer> spiralOrder(int[][] matrix) {
		List<Integer> result=new LinkedList<>();
		if(matrix.length==0) return result;
        int iMin=0,iMax=matrix.length-1,jMin=0,jMax=matrix[0].length-1;
        int i=0,j=0;
        while(i>=iMin&&i<=iMax&&j>=jMin&&j<=jMax){
        	while(j<=jMax){
        		result.add(matrix[iMin][j++]);
        	}
        	iMin++;i=iMin;
        	while(i<=iMax){
        		result.add(matrix[i++][jMax]);
        	}
        	jMax--;j=jMax;
        	while(j>=jMin&&iMax>=iMin){
        		result.add(matrix[iMax][j--]);
        	}
        	iMax--;i=iMax;
        	while(i>=iMin&&jMin<=jMax){
        		result.add(matrix[i--][jMin]);
        	}
        	jMin++;j=iMin;i++;
        }
        return result;
    }
	
	public static void main(String[] args){
		System.out.println(new MySolution().spiralOrder(new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}}));
	}
}
